package com.sagereal.wtc.factorymode.Activity;

import androidx.appcompat.app.ActionBar;

import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.ListView;

import com.sagereal.wtc.factorymode.Adapter.TestReportAdapter;
import com.sagereal.wtc.factorymode.R;
import com.sagereal.wtc.factorymode.db.DatabaseManager;

import java.util.ArrayList;
import java.util.List;

public class TestReportActivity extends BaseActivity {
    private static final int REQUEST_CODE_KEY = 1; // 请求码
    private ListView mUntestListView,mPassListView,mFailListView;
    private List<Item> mUntestItemList,mPassItemList,mFailItemList;
    private TestReportAdapter mUntestAdapter,mPassAdapter,mFailAdapter;
    private DatabaseManager mDbManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);  // 添加返回的图标
        }
        setContentView(R.layout.activity_test_report);
        setTitle(getString(R.string.test_report));

        mDbManager = new DatabaseManager(this);
        initView();
        loadResultsFromDatabase();
    }

    private void initView() {
        mUntestListView = findViewById(R.id.testreport_untest_list);
        mUntestItemList = new ArrayList<>();
        mPassListView = findViewById(R.id.testreport_pass_list);
        mPassItemList = new ArrayList<>();
        mFailListView = findViewById(R.id.testreport_fail_list);
        mFailItemList = new ArrayList<>();
        // 初始化未测试列表
        mUntestItemList.add(new Item(getString(R.string.title_battery_test), "untest","battery"));
        mUntestItemList.add(new Item(getString(R.string.title_vibration_test), "untest","vibration"));
        mUntestItemList.add(new Item(getString(R.string.title_mic_test), "untest","mic"));
        mUntestItemList.add(new Item(getString(R.string.title_headset_test), "untest","headset"));
        mUntestItemList.add(new Item(getString(R.string.title_lcd_test), "untest", "lcd"));
        mUntestItemList.add(new Item(getString(R.string.title_speaker_test), "untest", "speaker"));
        mUntestItemList.add(new Item(getString(R.string.title_receiver_test), "untest", "receiver"));
        mUntestItemList.add(new Item(getString(R.string.title_camera_test), "untest", "camera"));
        mUntestItemList.add(new Item(getString(R.string.title_flash_test), "untest", "flash"));
        mUntestItemList.add(new Item(getString(R.string.title_key_test), "untest", "key"));
        mUntestItemList.add(new Item(getString(R.string.title_brightness_test), "untest", "brightness"));

        mUntestAdapter = new TestReportAdapter(TestReportActivity.this, R.layout.item, mUntestItemList);
        mUntestListView.setAdapter(mUntestAdapter);

        mPassAdapter = new TestReportAdapter(TestReportActivity.this, R.layout.item, mPassItemList);
        mPassListView.setAdapter(mPassAdapter);

        mFailAdapter = new TestReportAdapter(TestReportActivity.this, R.layout.item, mFailItemList);
        mFailListView.setAdapter(mFailAdapter);

        mUntestListView.setOnItemClickListener((adapterView, view, i, l) -> {
            startTestActivity(mUntestItemList.get(i), i);
        });

        mPassListView.setOnItemClickListener((adapterView, view, i, l) -> {
            startTestActivity(mPassItemList.get(i), i);
        });

        mFailListView.setOnItemClickListener((adapterView, view, i, l) -> {
            startTestActivity(mFailItemList.get(i), i);
        });
    }

    private void startTestActivity(Item item, int position) {
        Intent intent = new Intent();
        switch (item.getCheck()) {
            case "battery":
                intent.setClass(TestReportActivity.this, BatteryActivity.class);
                break;
            case "vibration":
                intent.setClass(TestReportActivity.this, VibrationActivity.class);
                break;
            case "mic":
                intent.setClass(TestReportActivity.this, MicActivity.class);
                break;
            case "headset":
                intent.setClass(TestReportActivity.this, HeadsetActivity.class);
                break;
            case "lcd":
                intent.setClass(TestReportActivity.this, LcdActivity.class);
                break;
            case "speaker":
                intent.setClass(TestReportActivity.this, SpeakerActivity.class);
                break;
            case "receiver":
                intent.setClass(TestReportActivity.this, ReceiverActivity.class);
                break;
            case "camera":
                intent.setClass(TestReportActivity.this, CameraActivity.class);
                break;
            case "flash":
                intent.setClass(TestReportActivity.this, FlashActivity.class);
                break;
            case "key":
                intent.setClass(TestReportActivity.this, KeyActivity.class);
                break;
            case "brightness":
                intent.setClass(TestReportActivity.this, BrightnessActivity.class);
                break;
        }
        intent.putExtra("ItemId", position);
        intent.putExtra("status", item.getStatus());
        intent.putExtra("check", item.getCheck());
        startActivityForResult(intent, REQUEST_CODE_KEY);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_KEY && resultCode == RESULT_OK) {
            if (data != null) {
                int itemId = data.getIntExtra("ItemId", -1);
                String status = data.getStringExtra("status");
                String check = data.getStringExtra("check");
                // 更新数据
                if (status != null) {
                    if ("pass".equals(status)) {
                        updateTestItemStatus(itemId, status, check, mPassItemList);
                    } else if ("fail".equals(status)) {
                        updateTestItemStatus(itemId, status, check, mFailItemList);
                    }
                    // 重新加载所有列表
                    loadResultsFromDatabase();
                }
            }
        }
    }

    private void updateTestItemStatus(int itemId, String status, String check, List<Item> targetList) {
        Item item = null;

        // 从未测试列表中移除
        if (itemId >= 0 && itemId < mUntestItemList.size()) {
            item = mUntestItemList.get(itemId);
        }
        // 从通过列表中移除
        if (item == null && itemId >= 0 && itemId < mPassItemList.size()) {
            item = mPassItemList.get(itemId);
        }
        // 从失败列表中移除
        if (item == null && itemId >= 0 && itemId < mFailItemList.size()) {
            item = mFailItemList.get(itemId);
        }

        if (item != null) {
            item.setStatus(status);
            item.setCheck(check);
            mDbManager.saveResult(item.getName(), status, check);

            // 从所有列表中移除项目
            mUntestItemList.remove(item);
            mPassItemList.remove(item);
            mFailItemList.remove(item);

            // 将项目添加到目标列表
            if ("pass".equals(status)) {
                mPassItemList.add(item);
            } else if ("fail".equals(status)) {
                mFailItemList.add(item);
            } else {
                mUntestItemList.add(item);
            }

            // 更新列表视图
            mUntestAdapter.notifyDataSetChanged();
            mPassAdapter.notifyDataSetChanged();
            mFailAdapter.notifyDataSetChanged();
            // 更新设置当前语言
            applySavedLanguage();
        }
    }

    private void loadResultsFromDatabase() {
        // 清空所有列表
        mUntestItemList.clear();
        mPassItemList.clear();
        mFailItemList.clear();
        // 初始化未测试列表
        List<Item> loadedUntestList = new ArrayList<>();
        loadedUntestList.add(new Item(getString(R.string.title_battery_test), "untest", "battery"));
        loadedUntestList.add(new Item(getString(R.string.title_vibration_test), "untest", "vibration"));
        loadedUntestList.add(new Item(getString(R.string.title_mic_test), "untest", "mic"));
        loadedUntestList.add(new Item(getString(R.string.title_headset_test), "untest", "headset"));
        loadedUntestList.add(new Item(getString(R.string.title_lcd_test), "untest", "lcd"));
        loadedUntestList.add(new Item(getString(R.string.title_speaker_test), "untest", "speaker"));
        loadedUntestList.add(new Item(getString(R.string.title_receiver_test), "untest", "receiver"));
        loadedUntestList.add(new Item(getString(R.string.title_camera_test), "untest", "camera"));
        loadedUntestList.add(new Item(getString(R.string.title_flash_test), "untest", "flash"));
        loadedUntestList.add(new Item(getString(R.string.title_key_test), "untest", "key"));
        loadedUntestList.add(new Item(getString(R.string.title_brightness_test), "untest", "brightness"));
        // 加载数据库中的结果
        for (Item item : loadedUntestList) {
            String status = mDbManager.getResult(item.getCheck());
            item.setStatus(status);
            if ("pass".equals(status)) {
                mPassItemList.add(item);
            } else if ("fail".equals(status)) {
                mFailItemList.add(item);
            } else {
                mUntestItemList.add(item);
            }
        }
        // 更新列表视图
        mUntestAdapter.notifyDataSetChanged();
        mPassAdapter.notifyDataSetChanged();
        mFailAdapter.notifyDataSetChanged();
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish(); // 返回上一个界面
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mDbManager.close();
    }
}
